import {
	defineStore
} from 'pinia'
export const useUserIm = defineStore('im', {
	state: () => {
		return {
			connectCount: 0, // WebSocket 连接次数
			MAX_CONNECT_COUNT: 5, // 最大重连次数
			timer: 0, //计时器
			imToken: uni.getStorageSync('imToken'), // 聊天token
			ws: '', // websock对象
			imSelfAvatar: '', // 用户头像信息
			imTargetUserinfo: {}, // 对方用户信息
			imChatid: '',
			messagelist: [], // 消息列表
			imShowParams: {}, // 会话列表跳转 聊天页面所需参数
			sendScrollState: false, // 区分上下拉加载还是 发送消息设置 滚动条
			isInBlackObj: {
				chatid: '',
				cancel_enable: '2',
				message: ''
			}, // 是否在黑名单中
			IsUpdataChatList: 0, // 不是同一个人聊天则需要更新会话列表
			imUnreaded: false, // 未读消息状态
		}
	},
	actions: {
		// 设置聊天id
		setimChatid(chatid) {
			this.imChatid = chatid
		},
		// 添加黑名单
		getBlacklistAdd(chatid) {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken,
					chatid
				}
				let config = {
					custom: {
						loading: true
					}
				}
				let res = await uni.$u.api.getBlacklistAdd(params, config)
				resolve(res)
			})
		},
		// 解除黑名单
		getBlacklistDel(chatid) {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken,
					chatid
				}
				let config = {
					custom: {
						loading: true
					}
				}
				let res = await uni.$u.api.getBlacklistDel(params, config)
				resolve(res)
			})
		},
		// 检测对方是否在黑名单
		getBlacklistCheck(chatid) {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken,
					chatid
				}
				let config = {
					custom: {
						loading: true
					}
				}
				let res = await uni.$u.api.getBlacklistCheck(params, config)
				resolve(res)
			})
		},
		// 删除聊天
		getRemoveChat(chat_id) {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken,
					chat_id
				}
				let res = await uni.$u.api.getRemoveChat(params)
				uni.$u.toast("删除成功")
				resolve()
			})
		},
		// 是否置顶
		getChatStick(chat_id, stick) {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken,
					chat_id,
					stick: stick == 1 ? 0 : 1
				}
				let res = await uni.$u.api.getChatStick(params)
				uni.$u.toast(stick == 1 ? '取消置顶成功' : '置顶成功')
				resolve()
			})
		},
		// 获取用户列表
		getUserList() {
			return new Promise(async (resolve, reject) => {
				let params = {
					token: this.imToken
				}
				let res = await uni.$u.api.getChatList(params)
				uni.hideTabBarRedDot({
					index: 1
				})
				res.items.forEach(item => {
					if (item.new > 0) {
						uni.showTabBarRedDot({
							index: 1
						})
					}
				})
				resolve(res.items)
			})
		},
		ping() {
			var msgObj = {
				controller: 'Ping',
				action: 'index',
				args: {}
			}
			this.webSocket_send(msgObj)
		},
		// 检测全局聊天是否开启
		imWindowGlobal() {
			return new Promise(async (resolve, reject) => {
				let res = await uni.$u.api.imWindowGlobal()
				if (res.next == '') {
					await this.setImToken()
					setTimeout(() => {
						this.timer = setInterval(this.ping, 50000)
					}, 10)
				}
				resolve()
			})
		},
		// 获取imToken
		setImToken() {
			return new Promise(async (resolve, reject) => {
				let res = await uni.$u.api.getImToken()
				if (res) {
					this.imToken = res
					uni.setStorageSync('imToken', res)
					this.initWebSocket(res)
				}
				resolve()
			})
		},
		// 更新消息列表
		setChatList(data) {
			function isJSON(str) {
				if (typeof str == 'string') {
					try {
						var obj = JSON.parse(str)
						if (typeof obj == 'object' && obj) {
							return true
						} else {
							return false
						}
					} catch (e) {
						return false
					}
				}
			}
			if (isJSON(data.data)) {
				this.imUnreaded = true
				// 当消息返回错误信息时
				if (data.error !== undefined) {
					uni.$u.toast(data.error)
					return false
				}
				let mesData = JSON.parse(data.data)
				let message = isJSON(mesData.content) ? JSON.parse(mesData.content) : mesData.content
				// 屏蔽对方 / 被对方屏蔽
				if (mesData.type == 'isInBlacklist') {
					if (mesData.cancel_enable == 1) {
						this.isInBlackObj = {
							chatid: mesData.chatid,
							cancel_enable: mesData.cancel_enable,
							message: mesData.content
						}
					} else if (mesData.cancel_enable == 0) {
						this.isInBlackObj = {
							chatid: mesData.chatid,
							cancel_enable: mesData.cancel_enable,
							message: mesData.content
						}
					} else {
						this.isInBlackObj = {
							chatid: '',
							cancel_enable: '2',
							message: ''
						}
					}
					return false
				}
				// id 相同说明是同一个人 则需要处理数据
				if (this.imChatid == mesData.chatid) {
					if (mesData.type == 'return_receipt_one') {
						this.messagelist.forEach((element, index) => {
							if (element.messageid == message.messageid) {
								this.messagelist[index].readed = 1
							}
						})
					} else if (mesData.type == 'return_receipt_all') {
						this.messagelist.forEach((element, index) => {
							this.messagelist[index].readed = 1
						})
					} else {
						var addObj = {
							self_side: mesData.self_side,
							avatar: mesData.self_side == 1 ? this.imSelfAvatar : this.imTargetUserinfo
								.avatar,
							type: mesData.type,
							message: message,
							addtime: mesData.addtime,
							readed: 0,
							messageid: mesData.messageid
						}
						if (mesData.replace == 1) {
							this.messagelist.forEach((item) => {
								if (item.messageid == mesData.messageid) {
									if (isJSON(mesData.content)) {
										item.message = JSON.parse(mesData.content)
									} else {
										item.message = mesData.content
									}
								}
							})
						} else {
							this.messagelist.push(addObj)
							if (mesData.self_side == 1) {} else {
								/**
								 * 发送回执
								 */
								var pages = getCurrentPages();
								var page = pages[pages.length - 1];
								// #ifdef MP-WEIXIN
								if (page.$page.fullPath == 'pages/pagesMessage/detail') {
									var msgObj = {
										controller: 'SendReturnReceipt',
										action: 'one',
										args: {
											token: this.imToken,
											messageid: mesData.messageid
										}
									}
									var msgStr = JSON.stringify(msgObj)
									this.ws.send(msgStr)
								}
								// #endif
								// #ifndef MP-WEIXIN
								if (page.$page.path == 'pages/pagesMessage/detail') {
									var msgObj = {
										controller: 'SendReturnReceipt',
										action: 'one',
										args: {
											token: this.imToken,
											messageid: mesData.messageid
										}
									}
									var msgStr = JSON.stringify(msgObj)
									this.ws.send(msgStr)
								}
								// #endif

							}
						}
					}
				} else {
					// 不是同一个人 添加红点
					this.IsUpdataChatList += 1
				}
			}
		},
		// IM初始化并登录
		initWebSocket(value) {
			// #ifndef H5
			this.ws = uni.connectSocket({
				url: 'wss://imserv.v2.74cms.com',
				complete: () => {}
			})
			uni.onSocketOpen((res) => {
				var msgObj = {
					controller: 'Connect',
					action: 'index',
					args: {
						token: value
					}
				}
				var msgStr = JSON.stringify(msgObj)
				uni.sendSocketMessage({
					data: msgStr
				});
				console.log('WebSocket连接已打开！');
			});
			uni.onSocketMessage((res) => {
				this.setChatList(res)
			});
			uni.onSocketError((res) => {
				this.reconnect()
				console.log('WebSocket连接打开失败，请检查！');
			});
			uni.onSocketClose((res) => {
				this.reconnect()
				console.log('WebSocket 已关闭！');
			});
			// #endif
			// #ifdef H5
			this.ws = new WebSocket('wss://imserv.v2.74cms.com')
			this.ws.onopen = async () => {
				var msgObj = {
					controller: 'Connect',
					action: 'index',
					args: {
						token: value
					}
				}
				var msgStr = JSON.stringify(msgObj)
				this.ws.send(msgStr)
				console.log('连接成功')
			}
			this.ws.onmessage = (e) => {
				this.setChatList(e)
			}
			this.ws.onerror = (error) => {
				console.log('连接失败：', error)
				this.reconnect()
			}
			this.ws.onclose = (e) => {
				this.reconnect()
				console.log('连接关闭', e)
			}
			// #endif
		},
		// WebSocket 重连
		reconnect() {
			this.connectCount++;
			if (this.connectCount > this.MAX_CONNECT_COUNT) {
				console.log('WebSocket 重连次数已达上限');
				return;
			}

			console.log('WebSocket 3 秒后进行第', this.connectCount, '次重连');
			setTimeout(() => {
				this.initWebSocket(this.imToken)
			}, 3000);
		},
		// websocket 发送消息
		webSocket_send(value) {
			var msgObj = JSON.stringify(value)
			if (
				value.controller == 'SendInvite' ||
				value.controller == 'SendWechat' ||
				value.controller == 'SendMobile' ||
				value.controller == 'SendMap' ||
				value.controller == 'SendResume' ||
				value.controller == 'SendJob' ||
				value.controller == 'SendText' ||
				value.controller == 'SendImage') {
				this.sendScrollState = true
				this.appPushInfo(value.args)
			}
			// #ifdef H5
			this.ws.send(msgObj)
			// #endif
			// #ifndef H5
			uni.sendSocketMessage({
				data: msgObj
			});
			// #endif
		},
		// 推送
		appPushInfo(data) {
			return new Promise((resolve) => {
				uniCloud.callFunction({
					name: 'uni-push',
					data: {
						cids: data.cids,
						title: data.title,
						content: data.content,
						data,
						request_id: uni.$u.guid(),
					}
				}).then((res) => {
					resolve(res.success)
				}).catch(() => {
					resolve(false);
				})
			});
		}
	},

	// #ifdef H5
	persist: {
		enabled: true,
		strategies: [{
			key: 'im',
			storage: localStorage
		}]

	}
	// #endif
})